const path = require('path')
const fs = require('fs')
const moment = require('moment')
const ArtController = {};
const {
    promisify
} = require('util')

// 导入模型
const viewsDir = path.join(path.dirname(__dirname), 'views')
const query = require('../model/query.js')
const rename = promisify(fs.rename)


ArtController.index = (req, res) => {
    res.render(`articlelist.html`)
}

ArtController.systemData = async (req, res) => {
    const sql = 'select * from settings';
    const rows = await query(sql)
    res.json(rows)
}

ArtController.artData = async (req, res) => {
    // 1. 接收页码和每页显示的条数
    const {
        page,
        limit
    } = req.query;
    // 2. 查询总记录数
    const sql1 = 'select count(id) as count from article'
    const result = await query(sql1)
    const {
        count
    } = result[0]
    // 3. 根据page和limit获取指定页码的数据
    // a b c d e f g H i j k 每页显示2条
    // 第1页 a b 、 第2页、 c d  ... 3页 e f 、4页 H i   5页 j k
    // 查询起始位置 : （当前页-1）* 每页显示的条数
    // page=1 offset = 0,2
    // page=2 offset = 2,2
    // page=3 offset = 4,2
    // page=4 offset = 6,2
    // page=5 offset = 8,2

    const offset = (page - 1) * limit;
    const sql2 = `select t1.*,t2.cate_name,t3.username from article t1 
        left join category t2 on t1.cate_id = t2.cate_id 
        left join users t3 on t1.author = t3.id
        order by t1.id desc
        limit ${offset},${limit}`
    let data = await query(sql2)
    data = data.map((item) => {
        const {
            add_date,
            status,
            cate_name,
            username
        } = item;
        item.statusText = status == 1 ? '审核通过' : "审核中"
        item.cate_name = cate_name || '未分类'
        item.username = username || '匿名者'
        item.add_date = moment(add_date).format('YYYY-MM-DD HH:mm:ss')
        return item;
    })
    // 4. 响应数据
    res.json({
        count,
        data,
        code: 0,
        msg: "sucess"
    })
}

ArtController.delArtData = async (req, res) => {
    const {
        id
    } = req.body;
    const sql = `delete from article where id = ${id}`
    const {
        affectedRows
    } = await query(sql)
    // 删除文章的封面图，自行完成
    if (affectedRows > 0) {
        res.json({
            code: 0,
            message: "delete sucess"
        })
    } else {
        res.json({
            code: -7,
            message: "delete fail"
        })
    }
    // return false; // Promise.resolve(false)会进行包装返回
}

ArtController.addArticle = (req, res) => {
    res.render('addArticle.html')
}

ArtController.addArtData = async (req, res) => {
    // 1. 接收参数
    const {
        title,
        cate_id,
        status,
        content
    } = req.body;
    // to do .....
    const add_date = moment().format('YYYY-MM-DD HH:mm:ss')
    const author = req.session.userInfo.id;
    let pic = '';
    // 上传文件
    if (req.file) {
        // 2. 上传文件得到路径
        let {
            destination,
            originalname,
            filename
        } = req.file;
        let extName = originalname.substring(originalname.lastIndexOf('.'))
        let uploadDir = './uploads'
        let oldName = path.join(uploadDir, filename);
        let newName = path.join(uploadDir, filename) + extName;

        try {
            const result = await rename(oldName, newName)
            pic = `uploads/${filename}${extName}`

        } catch (err) {
            console.log('上传失败')
        }


    }
    //2. 编写sql语句
    let sql = `insert into article(title,cate_id,status,content,add_date,author,pic) 
            values('${title}','${cate_id}','${status}','${content}','${add_date}','${author}','${pic}')`
    const {
        affectedRows
    } = await query(sql)
    //3. 返回结果
    if (affectedRows > 0) {
        res.json({
            code: 0,
            message: '添加文章成功'
        })
    } else {
        res.json({
            code: -7,
            message: '添加文章失败'
        })
    }
}

ArtController.editPassword = async (req, res) => {
    res.render('editPassword.html')
}

//旧密码
ArtController.isoldPassword = async (req, res) => {
    let { password } = req.body;
    let { id } = req.params
    password = md5(`${password}${password_secret}`);
    const sql = `select password from users where id= ${id}`;
    const rows = await query(sql);
    const sqlPassword = rows[0].password;
    if (password === sqlPassword) {
        res.json({
            code: 0,
            message: '密码正确'
        })
    } else {
        res.json({
            code: 1,
            message: '密码错误'
        })
    }
}

//新密码
ArtController.updpassword = async (req, res) => {
    let { pass } = req.body;
    let { id } = req.params;
    pass = md5(`${pass}${password_secret}`);
    const sql = `update users set password = '${pass}' where id = ${id}`
    const rows = await query(sql);
    const { affectedRows } = rows
    if (affectedRows > 0) {
        req.session.destroy(function (err) {
            if (err) {
                throw err;
            }
        })
        res.json({
            code: 0,
            message: "修改成功"
        })
    } else {
        res.json({
            code: 1,
            message: "修改失败"
        })
    }
}

module.exports = ArtController;